﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Lenovo.CFI.BLL;
using Lenovo.CFI.BLL.DicMgr;
using Lenovo.CFI.Common;
using Lenovo.CFI.Web.Helper;
using TB.Web.UI.WebControls;

namespace Lenovo.CFI.Web.VP
{
    public partial class MyIdeaList : System.Web.UI.UserControl
    {
        IdeaBl ideaBl = new IdeaBl();
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                BindHelper.BindTopics(DdlTopic, "Select...", "-1", null);
                BindHelper.BindIdeaType(DdlType, "Select...", "-1", null, true);
                BindHelper.BindNextAction(DdlSuggestion, "Select...", "-1", null, true);

                this.BtnAdd.OnClientClick = "alert('Please select ongoing topic to submit new idea!');";

                this.BindData();

                MessageHelper.Prepare(this.Page);
            }
        }

        protected void BtnFilter_Click(object sender, EventArgs e)
        {
            ViewState["Topic"] = this.DdlTopic.SelectedValue;
            ViewState["Type"] = this.DdlType.SelectedValue;
            ViewState["Action"] = this.DdlSuggestion.SelectedValue;
            ViewState["ActionStatus"] = this.DdlEStatus.SelectedValue;

            if (this.DdlTopic.SelectedIndex != 0)
            {
                Topic topic = new TopicBl().GetTopicByID(Convert.ToInt32(this.DdlTopic.SelectedValue));
                if (topic.Status == TopicStatus.Start && DateTime.Now > topic.StartTime)
                {
                    this.BtnAdd.OnClientClick = String.Format("window.open('{0}')", UrlHelper.GenerateUrl("myideanew", "tid", this.DdlTopic.SelectedValue));
                }
                else
                {
                    this.BtnAdd.OnClientClick = "alert('Please select ongoing topic to submit new idea!');";
                }
            }
            else
            {
                this.BtnAdd.OnClientClick = "alert('Please select ongoing topic to submit new idea!');";
            }

            this.BindData();
        }


        List<Topic> topics = null;
        private void BindData()
        {
            string owner = UserHelper.UserName;

            int? topicID = null;
            if (ViewState["Topic"] != null) topicID = Convert.ToInt32(ViewState["Topic"]);
            if (topicID == -1) topicID = null;

            string ideaType = null;
            if (ViewState["Type"] != null) ideaType = (string)ViewState["Type"];
            if (ideaType == "-1") ideaType = null;


            string nextAction = null;
            if (ViewState["Action"] != null) nextAction = (string)ViewState["Action"];
            if (nextAction == "-1") nextAction = null;

            int? nextActionStatus = null;
            if (ViewState["ActionStatus"] != null) nextActionStatus = Convert.ToInt32(ViewState["ActionStatus"]);
            if (nextActionStatus == -1) nextActionStatus = null;

            topics = new TopicBl().GetTopic();

            GvList.DataSource = ideaBl.GetIdeaForOwner(UserHelper.UserName, topicID, ideaType, null, nextAction, nextActionStatus);
            GvList.DataBind();
        }

        protected void GvList_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            if (e.Row.RowType == DataControlRowType.DataRow)
            {
                // 设置行号
                ((Literal)(e.Row.FindControl("LtrNo"))).Text = String.Format("{0}", e.Row.DataItemIndex + 1);


                Idea idea = (Idea)e.Row.DataItem;

                ((Literal)e.Row.FindControl("LtrTopic")).Text = (topics.Find(t=>t.ID == idea.TopicID)).No;
                ((Literal)e.Row.FindControl("LtrName")).Text = String.Format(@"<a href=""{0}"" target=""_blank"">{1}</a>{2}",
                    UrlHelper.GenerateUrl("myideadetail", "id", idea.ID.ToString()), idea.Title,
                    String.IsNullOrEmpty(idea.DcComment) ? "" : "* DC ");
                ((Literal)e.Row.FindControl("LtrDate")).Text = idea.SubmitTime.ToString("yyyy-MM-dd");
                ((Literal)e.Row.FindControl("LtrType")).Text = IdeaTypeDicMgr.GetByCode(idea.Type).Title;
                ((Literal)e.Row.FindControl("LtrPStatus")).Text = idea.StatusText;
                ((Literal)e.Row.FindControl("LtrSuggestion")).Text = idea.FinalAction == null ? "" : NextActionDicMgr.GetByCode(idea.FinalAction).Title;
                ((Literal)e.Row.FindControl("LtrEStatus")).Text = idea.FinalActionStatusText;


                HyperLink hlEdit = (HyperLink)e.Row.FindControl("HlEdit");
                ImageButton btnConfirm = (ImageButton)e.Row.FindControl("BtnConfirm");
                ConfirmImageButton btnDel = (ConfirmImageButton)e.Row.FindControl("BtnDel");

                //草稿状态可以删除
                btnDel.Visible = (idea.Status == IdeaStatus.Draft);


                //草稿状态、待审批状态、直接提交 可以修改
                if (idea.Status == IdeaStatus.Draft || idea.Status == IdeaStatus.Approving || idea.Status == IdeaStatus.Submitted || idea.Status == IdeaStatus.Agree)
                {
                    hlEdit.Visible = true;
                    hlEdit.NavigateUrl = UrlHelper.GenerateUrl("myideaedit", "id", idea.ID.ToString());
                }
                else
                    hlEdit.Visible = false;

                //评审准备状态下可以确认是否参加
                if (idea.Status == IdeaStatus.ReviewPreparing && idea.FinalReviewID.HasValue)
                {
                    // 性能问题 -- 数量不多，应该还可以接受
                    IdeaReview ideaReview = new ReviewBl().GetReviewByID(idea.FinalReviewID.Value);
                    if (ideaReview.OwnerConfirmed == null)
                    {
                        btnConfirm.Visible = true;

                        btnConfirm.CommandArgument = ideaReview.ID.ToString();
                    }
                    else
                        btnConfirm.Visible = false;
                }
                else
                    btnConfirm.Visible = false;
            }
        }

        protected void GvList_RowCommand(object sender, GridViewCommandEventArgs e)
        {
            if (e.CommandName == "Remove")
            {
                try
                {
                    ideaBl.Delete(Convert.ToInt32(e.CommandArgument));

                    MessageHelper.RegShowJSAjax(this.GvList, "Success!", this.Page);
                }
                catch (ApplicationException ex)
                {
                    MessageHelper.RegShowJSAjax(this.GvList, ex.Message, this.Page);
                }

                this.BindData();
            }
            else if (e.CommandName == "OwnerConfirm")   //owner确认参加
            {
                int reviewID = Convert.ToInt32(e.CommandArgument);
                ViewState["ReviewID"] = reviewID;

                IdeaReview ideaReview = new ReviewBl().GetReviewByID(reviewID);

                this.RblConfirm.SelectedValue = ideaReview.OwnerConfirmed.ToString();
                this.TxtComment.Text = ideaReview.OwnerConfirmComment;

                MpeConfirm.Show();
            }
        }

        protected void GvList_PageIndexChanging(object sender, GridViewPageEventArgs e)
        {
            this.GvList.PageIndex = e.NewPageIndex;
            this.BindData();
        }

        protected void BtnSave_Click(object sender, EventArgs e)
        {
            try
            {
                new ReviewBl().OwnerConfirm(Convert.ToInt32(ViewState["ReviewID"]), 
                    (this.RblConfirm.SelectedValue == "1"), this.TxtComment.Text.Trim());

                MessageHelper.RegShowJSAjax(this.BtnSave, "Success!", this.Page);
            }
            catch (ApplicationException ex)
            {
                MessageHelper.RegShowJSAjax(this.BtnSave, ex.Message, this.Page);
            }
            catch (Exception ex)            // Ajax无法使用默认异常处理程序处理异常
            {
                ErrorHelper.ExceptionHanderForAjax(ex, this.BtnSave, this.Page);
            }

            this.BindData();
        }
    }
}